package cn.znzz.cjm.exceptionhandle;

import cn.znzz.cjm.constants.GlobalStatusExceptionCode;
import cn.znzz.cjm.util.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice //aop的一种体现  相当于在controller有了切面
public class GlobalExceptionHandle {
    @ExceptionHandler(ArithmeticException.class)
    public AjaxResult mathException(ArithmeticException e){
        return AjaxResult.me().setSuccess(false).setMessage("算术异常信息："+e.getMessage()).setCode(GlobalStatusExceptionCode.CODE_400_PARAM_VALID.getCode());
    }

    @ExceptionHandler(RuntimeException.class)
    public AjaxResult mathException(RuntimeException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("异常信息："+e.getMessage());
    }
    /**
     * 处理jsr303校验未通过的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgsException(MethodArgumentNotValidException e){
        //获取参数校验未通过的字段
        BindingResult result = e.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        HashMap<String, Object> map = new HashMap<>();
        fieldErrors.stream().forEach((FieldError a)->{
            map.put(a.getField(),a.getDefaultMessage());
        });
        return AjaxResult.me().setSuccess(false).setMessage(map.toString()).setCode(HttpStatus.BAD_REQUEST.value());
    }
}
